﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Drawing;

namespace NotifyServices
{
    public class ServiceControllerButton: Button
    {
        public ServiceResponse Service;
        public ServiceController Controller;
        public AsynchronousServiceManager Manager;
        public delegate void OnFinish(ServiceResponse e);
        public event OnFinish Finished;

        public string ServiceName
        {
            get
            {
                return Controller.DisplayName;
            }
        }
        public ServiceControllerButton(string host, string service)
        {
            Controller = new ServiceController(service, host);
            Manager = new AsynchronousServiceManager();
            Manager.Finished += new AsynchronousServiceManager.OnFinish(Manager_Finished);

            Service = new ServiceResponse() { 
                Host = host, 
                Service = service, 
                CurrentStatus = Controller.Status.ToString() ,
                Name = Controller.DisplayName
            };

            UpdateImageOnStatus();
            Width = Image.Width+10;
            Height = Image.Height+10;
        }

        public void UpdateImageOnStatus()
        {
            if (Controller.Status == ServiceControllerStatus.Stopped)
                Image = (Image)Properties.Resources.play.ToBitmap();
            else if (Controller.Status == ServiceControllerStatus.Running)
                Image = (Image)Properties.Resources.stop.ToBitmap();
        }
        public void UpdateService()
        {
            if (Service.CurrentStatus == "Running")
                Manager.Update(Service.Service, Service.Host, "STOP");
            else if (Service.CurrentStatus == "Stopped")
                Manager.Update(Service.Service, Service.Host, "START");
            Image = (Image)Properties.Resources.loader_violet;

        }
        void Manager_Finished(ServiceResponse r)
        {
            Service = r;
            Controller = new ServiceController(r.Service, r.Host);
            UpdateImageOnStatus();
            OnFinish handler = Finished;
            handler(r);
        }
    }
}
